package cn.com.aiouyi.plugin.localStorage;

import cn.com.aiouyi.common.ExceptionCode;
import cn.com.aiouyi.common.Message;
import cn.com.aiouyi.entity.Accessory;
import cn.com.aiouyi.entity.PluginConfig;
import cn.com.aiouyi.entity.SystemExceptionLog;
import cn.com.aiouyi.exception.business.BusinessException;
import cn.com.aiouyi.exception.system.SystemException;
import cn.com.aiouyi.plugin.StoragePlugin;
import cn.com.aiouyi.service.AccessoryService;
import cn.com.aiouyi.util.CommUtil;
import cn.com.aiouyi.util.FileHelper;
import cn.com.aiouyi.util.LogHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.ServletContextAware;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Plugin - 本地文件存储
 * 
 * @author SHOP++ Team
 * @version 4.0
 */
@Slf4j
@Component("localStoragePlugin")
public class LocalStoragePlugin extends StoragePlugin implements ServletContextAware {


    @Resource
    private HttpServletRequest fetchedRequest;

	/** ServletContext */
	private ServletContext servletContext;

	@Resource(name = "accessoryServiceImpl")
	private AccessoryService accessoryService;

    /** 文件设置的字段名 */
    private static final String ATTRIBUTE_IMAGEFILEPATH = "imageFilePath";
    private static final String ATTRIBUTE_VIDEOFILEPATH = "videoFilePath";
    private static final String ATTRIBUTE_TEXTFILEPATH = "textFilePath";
    private static final String ATTRIBUTE_MAXSIZE = "maxSize";
    private static final String ATTRIBUTE_IMAGEFILESUFFIX = "imageFileSuffix";
    private static final String ATTRIBUTE_TEXTFILESUFFIX = "textFileSuffix";
    private static final String ATTRIBUTE_VIDEOFILESUFFIX = "videoFileSuffix";

	/**
	 * 设置ServletContext
	 * 
	 * @param servletContext
	 *            ServletContext
	 */
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	@Override
	public String getName() {
		return "本地文件存储";
	}

	@Override
	public String getVersion() {
		return "1.0";
	}

	@Override
	public String getAuthor() {
		return "艾欧翼";
	}

	@Override
	public String getSiteUrl() {
		return "http://www.aiouyi.com.cn";
	}

	@Override
	public String getInstallUrl() {
		return null;
	}

	@Override
	public String getUninstallUrl() {
		return null;
	}

	@Override
	public String getSettingUrl() {
		return "local_storage/setting.jhtml";
	}

	public String getRootpath(){
		PluginConfig pluginConfig = getPluginConfig();
		if (pluginConfig.getAttributes()!=null
				&& StringUtils.isNotBlank(pluginConfig.getAttribute(ATTRIBUTE_TEXTFILEPATH))){
			return pluginConfig.getAttribute(ATTRIBUTE_TEXTFILEPATH);
		} else {
			String path = System.getProperty("user.dir");
			return path;
		}
	}

	public String generatePath(){
		StringBuffer rootpath = new StringBuffer(getRootpath());
		rootpath.append(File.separator).append(CommUtil.formatShortDate(new Date())).append(File.separator);
		return rootpath.toString();
	}

	@Override
	@Transactional
	public Message upload(String path, File file, FileType fileType) {
        try {
//            if (!fileSuffixValidation(file.getName(), fileType)){
//                throw new BusinessException(ExceptionCode.FileSuffixInvalid);
//            }
			String ext = FileHelper.getSuffix(file.getName());
			String newFilename = UUID.randomUUID().toString();
			path += newFilename + "." + ext;

			Accessory accessory = new Accessory();
			accessory.setExt(FileHelper.getSuffix(file.getName()));
            accessory.setOriginName(file.getName());
            accessory.setName(newFilename);
			accessory.setPath(path);

			accessory = accessoryService.save(accessory);

			if (accessory.getId() != null) {
				File destFile = new File(fetchedRequest.getServletContext().getResource(path).getFile());

				FileUtils.moveFile(file, destFile);

				Map<String, Object> map = new HashMap<>();
				map.put("id", accessory.getId());
				map.put("path", accessory.getPath());
				return Message.successData("上传成功", map);
			} else {
				throw new SystemException(ExceptionCode.FileUploadFail);
			}
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (BusinessException e){
            log.warn(LogHelper.logger(LogHelper.Type.WARN, ExceptionCode.FileSuffixInvalid, e, "plugin-文件后缀不符合要求", null, true, false));
        } catch (SystemException e){
			log.warn(LogHelper.logger(LogHelper.Type.WARN, ExceptionCode.FileUploadFail, e, "plugin-文件上传失败", null, true, false));
		}
		return Message.error("上传失败");
	}

	/**
     * 哈哈哈哈
     * */
    @Override
    public Message upload(String path, String originName, InputStream is, FileType fileType) {
        try {
//            if (!fileSuffixValidation(originName, fileType)){
//                throw new BusinessException(ExceptionCode.FileSuffixInvalid);
//            }

            String ext = FileHelper.getSuffix(originName);
            String newFilename = UUID.randomUUID().toString();
            path += newFilename + "." + ext;

			Accessory accessory = new Accessory();
			accessory.setExt(FileHelper.getSuffix(originName));
			accessory.setName(newFilename);
            accessory.setOriginName(originName);
			accessory.setPath(path);

			accessory = accessoryService.save(accessory);
			if (accessory.getId() != null) {
				File destFile = new File(fetchedRequest.getServletContext().getRealPath(path));
				FileUtils.copyInputStreamToFile(is, destFile);

				Map<String, Object> map = new HashMap<>();
				map.put("id", accessory.getId());
				map.put("path", accessory.getPath());
				return Message.successData("上传成功", map);
			} else {
				throw new SystemException(ExceptionCode.FileUploadFail);
			}
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (BusinessException e){
            log.warn(LogHelper.logger(LogHelper.Type.WARN, ExceptionCode.FileSuffixInvalid, e, "plugin-文件后缀不符合要求", null, true, false));
        } catch (SystemException e){
			log.warn(LogHelper.logger(LogHelper.Type.WARN, ExceptionCode.FileUploadFail, e, "plugin-文件上传失败", null, true, false));
		}
        return Message.error("上传失败");
    }

    @Override
	public String getUrl(String path) {
        PluginConfig pluginConfig = getPluginConfig();
		return "";
	}

	@Override
	public Boolean fileSuffixValidation(String filename, FileType fileType){
        PluginConfig pluginConfig = getPluginConfig();
        String realSuffix = FileHelper.getSuffix(filename);
//        String requiredSuffix = pluginConfig.getAttributes().get(fileType.name()+"FileSuffix");

        //如果文件没有后缀 直接判定不符合要求
        if (StringUtils.isEmpty(realSuffix)){
            return false;
        }

        //如果指定的后缀名为空 默认不限制
//        if (StringUtils.isEmpty(requiredSuffix)){
//            return true;
//        }
//
//        return FileHelper.isValidSuffix(filename, requiredSuffix);
        return false;
    }
}